package logic

import (
	"context"
	"furniture/furniturerpc/furniturerpc"
	"furniture/furniturerpc/internal/svc"
	"furniture/models"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddLogic) Add(in *furniturerpc.AddRequest) (*furniturerpc.AddResponse, error) {
	// todo: add your logic here and delete this line

	begin := models.DB.Debug().Begin()

	types := models.Types{
		Name: in.TypesName,
	}

	err := models.DB.Debug().Where("name = ?", in.TypesName).FirstOrCreate(&types).Error
	if err != nil {
		begin.Rollback()
		return nil, errors.New("类型添加失败")
	}

	brand := models.Brand{
		Name: in.BrandName,
	}

	err = models.DB.Debug().Where("name = ?", in.BrandName).FirstOrCreate(&brand).Error
	if err != nil {
		begin.Rollback()
		return nil, errors.New("品牌添加失败")
	}

	furniture := models.Furniture{
		Name:    in.Name,
		Price:   float64(in.Price),
		Address: in.Address,
		TypesId: int64(types.ID),
		BrandId: int64(brand.ID),
	}

	err = models.DB.Debug().Create(&furniture).Error

	if err != nil {
		begin.Rollback()
		return nil, errors.New("添加失败")
	}

	return &furniturerpc.AddResponse{
		FurnitureId: int64(furniture.ID),
	}, nil
}
